
package com.yunxi.common.config;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.rpc.RpcContext;
import com.alibaba.fastjson.JSONObject;
import com.yunxi.core.web.IgnoreSecurity;
import com.yunxi.core.web.JwtUtils;
import com.yunxi.core.web.LoginInfo;
import com.yunxi.core.web.ResponseUtil;
import com.yunxi.sys.pojo.UserVO;
import com.yunxi.sys.service.UserDubboService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Map;


/**
 * 功能描述：
 * Created by guan on 19/4/7.
 */

public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    RedisCacheService rcs;

    //@Autowired
    //TmUserService userService;

   @Autowired
    UserDubboService userDubboService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("html/text;charset=UTF-8");


        String requestPath = request.getRequestURI();

        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

       /* if (requestPath.contains("/v2/api-docs") || requestPath.contains("/swagger") || requestPath.contains("/configuration/ui")) {
            return true;
        }
*/
        if (requestPath.contains("/error")) {
            return true;
        }

        if (requestPath.contains("/service")) {
            return true;
        }

        if (requestPath.contains("/data")) {
            return true;
        }

        if (requestPath.contains("/api")) {
            return true;
        }

        if (requestPath.contains("/sso")) {
            return true;
        }
        if (requestPath.contains("/oss")) {
            return true;
        }
        if (requestPath.contains("/activiti")) {
            return true;
        }
        if (requestPath.contains("/admin/affiche")) {
            return true;
        }
        if (requestPath.contains("/admin/job")) {
            return true;
        }

        if (requestPath.contains("/admin/app/version/getNewVersion")) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        if (method.isAnnotationPresent(IgnoreSecurity.class)) {
            return true;
        }

        String token = request.getHeader("x-access-token");
        String roleCode = request.getHeader("roleCode");
        String tenantId = request.getHeader("tenantId");
        System.out.println("token: " + token);
        if (StringUtils.isEmpty(token)) {
            response.getWriter().write(JSONObject.toJSONString(ResponseUtil.fail(1000,"登录超时！access_token为空")));
            return false;
        }else{
            if(StringUtils.isNotEmpty(rcs.getString("token:"+token))){
                LoginInfo userInfo = JSONObject.parseObject(rcs.getString("token:"+token), LoginInfo.class);
                userInfo.setRoleCode(roleCode);
                userInfo.setTenantId(tenantId);
                request.setAttribute("currentUser", userInfo);
                /**
                 * 将当前用户信息保存到dubbo上下文 by xuruzi
                 */
                Map<String,String> attachments = RpcContext.getContext().getAttachments();
                RpcContext.getContext().setAttachment("currentUser",JSONObject.toJSONString(userInfo));

                if(userInfo.getIsOpen()!=null&&userInfo.getIsOpen()==1&&(
                        requestPath.contains("save")||
                        requestPath.contains("update")||
                        requestPath.contains("del")
                )){
                    response.getWriter().write(JSONObject.toJSONString(ResponseUtil.fail(1001,"当前没有操作权限！")));
                    return false;
                }
            }else{
                if(JwtUtils.validateJWT(token)!=null&&JwtUtils.validateJWT(token).getClaims()!=null){
                    String userid = JwtUtils.validateJWT(token).getClaims().getId();
                    UserVO user = userDubboService.getCasId(userid);
                    LoginInfo info = new LoginInfo();
                    info.setUser(user);
                    info.setRoleCode(roleCode);
                    info.setTenantId(tenantId);
                    request.setAttribute("currentUser", info);
                    /**
                     * 将当前用户信息保存到dubbo上下文 by xuruzi
                     */
                    RpcContext.getContext().setAttachment("currentUser", JSONObject.toJSONString(info));
                }else{
                    response.getWriter().write(JSONObject.toJSONString(ResponseUtil.fail(1000,"登录超时！access_token为空")));
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}

